// 解决默认 maker 无法显示的问题
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";

let DefaultIcon = L.icon({
  iconAnchor: [13, 41],
  iconUrl: icon,
  shadowUrl: iconShadow
});
L.Marker.prototype.options.icon = DefaultIcon;

let CursorStyle = "";
let polylineGroup = new L.FeatureGroup();
let polygonGroup = new L.FeatureGroup();

// 创建地图
const createMap = (divId, options) => {
  let map = L.map(divId, options);
  return map;
};

// 加载图层
const createTileLayer = async (map, url, options) => {
  let tileLayer = await L.tileLayer(url, options);
  tileLayer.addTo(map);
  return tileLayer;
};

// 改变鼠标样式
const addCursorStyle = (map, cursorStyle) => {
  CursorStyle = cursorStyle;
  L.DomUtil.addClass(map._container, cursorStyle);
};

const removerCoursorStyle = map => {
  if (CursorStyle) {
    L.DomUtil.removeClass(map._container, CursorStyle);
  }
};

/**
 * 创建线要素
 *
 * @param {Object} map
 * @param {Array} linePath
 * @param {Object} lineOpts
 */
const createPolyline = (map, linePath, lineOpts) => {
  let polyline = L.polyline(linePath, lineOpts);
  polylineGroup.addLayer(polyline)
  polylineGroup.addTo(map);
  return polyline;
};

/**
 * 创建面要素
 *
 * @param {Object} map
 * @param {Array} areaPath
 * @param {Object} areaOpts
 */
const createPolygon = (map, areaPath, areaOpts) => {
  let polygon = L.polygon(areaPath, areaOpts);
  polygonGroup.addLayer(polygon)
  polygonGroup.addTo(map);
  return polygon;
};

/**
 * 创建 Icon
 *
 * @param {Oject} options
 */
const createIcon = options => {
  return L.icon(options);
};

const createMakerByLatlng = (latlng, options) => {
  return L.marker(latlng, options);
};

const clearDrawnPolyGon = () => {
  polylineGroup.clearLayers()
  polygonGroup.clearLayers()
}

export default {
  createMap,
  createTileLayer,
  createIcon,
  createMakerByLatlng,
  createPolyline,
  createPolygon,
  addCursorStyle,
  removerCoursorStyle,
  clearDrawnPolyGon
};